package id.khairizalnetani.tugasakhir;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONObject;

import roboguice.activity.RoboActivity;
import roboguice.inject.InjectView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import id.khairizalnetani.tugasakhir.R;
import id.khairizalnetani.tugasakhir.entity.ErrorCheck;
import id.khairizalnetani.tugasakhir.entity.Keterangan;
import id.khairizalnetani.tugasakhir.entity.Laporan;
import id.khairizalnetani.tugasakhir.entity.Siswa;

public class Halaman3 extends RoboActivity implements OnClickListener
{
	// inisialisasi object di layout
	@InjectView(R.id.hal3TVSkadron)
	TextView					tvSkadronFLight;
	@InjectView(R.id.hal3TvPelapor)
	TextView					tvPelapor;
	@InjectView(R.id.hal3TVid)
	TextView					tvIdPelapor;
	@InjectView(R.id.hal3TVTanggal)
	TextView					tvTanggal;

	@InjectView(R.id.tvHal3JenisApel)
	TextView					tvJenisApel;
	@InjectView(R.id.tvhal3jumlahsiswa)
	TextView					tvJumlah;
	@InjectView(R.id.tvHal3Kurang)
	TextView					tvKurang;
	@InjectView(R.id.tvHal3Hadir)
	TextView					tvHadir;
	@InjectView(R.id.tvHal3DinasDalam)
	TextView					tvDinasDalam;
	@InjectView(R.id.tvHal3DinasLuar)
	TextView					tvDinasLuar;
	@InjectView(R.id.tvHal3Sakit)
	TextView					tvSakit;
	@InjectView(R.id.tvHal3Berobat)
	TextView					tvBerobat;
	@InjectView(R.id.tvHal3Izin)
	TextView					tvIzin;
	@InjectView(R.id.tvHal3TanpaKeterangan)
	TextView					tvTanpaKeterangan;

	@InjectView(R.id.hal3BtnLaporkan)
	Button						btnLaporkan;
	@InjectView(R.id.hal3BtnUbahData)
	Button						btnUbah;

	private long				id_report;
	private int					idSiswa;
	private String				tanggal;
	private int					jmlDD, jmlDL, jmlSakit, jmlBerobat, jmlIzin, jmlTk;

	public static final String	TAG_ID_REPORT		= "id_report";

	private ProgressDialog		pDialog;
	private Siswa				siswa;
	private DBAdapter			db;
	private List<Keterangan>	listKeterangan;

	private Laporan				laporan;
	private JSONHelper			json;
	private ErrorCheck			resultUpload;
	private static int			KODE_ERROR			= 0;	

	private final int			TXT_APEL_PAGI		= 0;
	private final int			TXT_APEL_SIANG		= 1;
	private final int			TXT_APEL_MALAM		= 2;

	private static final int	TXT_DINASDALAM		= 0;
	private static final int	TXT_DINASLUAR		= 1;
	private static final int	TXT_SAKIT			= 2;
	private static final int	TXT_BEROBAT			= 3;
	private static final int	TXT_IZIN			= 4;
	private static final int	TXT_TANPAKETERANGAN	= 5;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_halaman3);

		btnLaporkan.setOnClickListener(this);
		btnUbah.setOnClickListener(this);

		// instance object json helper untuk menangani proses upload
		json = new JSONHelper();
		// instance object db adapter
		db = new DBAdapter(this);
		db.open();

		// siswa = new Siswa();
		Bundle bundle = getIntent().getExtras();
		if (bundle != null)
		{
			id_report = bundle.getLong("id_report");
			idSiswa = bundle.getInt(Halaman1.TAG_ID);
		}

		// asynctask untk baca data dari sql
		new AsyncTaskHal3BacaDbSQl().execute();

	}

	// set tampilan
	private void setKeTampilan()
	{
		String txtFlight = null;
		String txtSkadron = null;
		switch (siswa.getFlight())
		{
			case 1:
				txtFlight = "Flight I";
				break;
			case 2:
				txtFlight = "Flight II";
				break;
			case 3:
				txtFlight = "Flight III";
				break;
			case 4:
				txtFlight = "Flight IV";
				break;
		}
		switch (siswa.getSkadron())
		{
			case 2:
				txtSkadron = "Skadron II";
				break;
			case 3:
				txtSkadron = "Skadron III";
				break;
			case 4:
				txtSkadron = "Skadron IV";
				break;
		}

		tvSkadronFLight.setText(txtFlight + " " + txtSkadron);
		tvPelapor.setText("Nama : " + siswa.getNama());
		tvIdPelapor.setText("ID : " + siswa.getId());
		setTanggal();
	}

	private void setDataKeTeksView()
	{
		tvJenisApel.setText(getJenisApel(laporan.getJenis_apel()));
		tvJumlah.setText(getValueOf(laporan.getJumlah()));
		tvKurang.setText(getValueOf(laporan.getKurang()));
		tvHadir.setText(getValueOf(laporan.getHadir()));
		tvDinasDalam.setText(getValueOf(jmlDD));
		tvDinasLuar.setText(getValueOf(jmlDL));
		tvSakit.setText(getValueOf(jmlSakit));
		tvBerobat.setText(getValueOf(jmlBerobat));
		tvIzin.setText(getValueOf(jmlIzin));
		tvTanpaKeterangan.setText(getValueOf(jmlTk));
	}

	private String getValueOf(int a)
	{
		return String.valueOf(a);
	}

	private String getJenisApel(int jenisApel)
	{
		switch (jenisApel)
		{
			case TXT_APEL_PAGI:
				return "Apel Pagi";

			case TXT_APEL_SIANG:
				return "Apel Siang";

			case TXT_APEL_MALAM:
				return "Apel Malam";
		}
		return null;
	}

	private void setTanggal()
	{
		SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy", Locale.US);

		tanggal = sdf.format(new java.util.Date());

		tvTanggal.setText(tanggal);

	}

	private String getTanggal()
	{
		// format tanggal harus seperti ini ---> 16/04/2013
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.US);

		tanggal = sdf.format(new java.util.Date());

		return tanggal;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.halaman3, menu);
		return true;
	}

	private class AsyncTaskHal3BacaDbSQl extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected Void doInBackground(Void... params)
		{
			laporan = new Laporan();
			Utils.TRACE("idReport " + id_report);
			// membaca data report dari sqlite
			laporan = db.getReportById(id_report);
			Utils.TRACE("idSiswa " + idSiswa);
			siswa = db.getSiswaById(idSiswa);
			jmlDD = db.getCountKeteranganByJenisAndIdReport(TXT_DINASDALAM, id_report);
			jmlDL = db.getCountKeteranganByJenisAndIdReport(TXT_DINASLUAR, id_report);
			jmlSakit = db.getCountKeteranganByJenisAndIdReport(TXT_SAKIT, id_report);
			jmlBerobat = db.getCountKeteranganByJenisAndIdReport(TXT_BEROBAT, id_report);
			jmlIzin = db.getCountKeteranganByJenisAndIdReport(TXT_IZIN, id_report);
			jmlTk = db.getCountKeteranganByJenisAndIdReport(TXT_TANPAKETERANGAN, id_report);

			listKeterangan = new ArrayList<Keterangan>();
			// membaca data keterangan dari sqlite
			listKeterangan = db.getKeteranganByIdReport(id_report);

			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			// TODO Auto-generated method stub

			pDialog.dismiss();
			setKeTampilan();
			setDataKeTeksView();

			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();

			pDialog = new ProgressDialog(Halaman3.this);
			pDialog.setMessage("Loading...");
			pDialog.setCancelable(true);
			pDialog.show();
		}
	}

	private class AsyncTaskHal3UploadKeWeb extends AsyncTask<Void, Void, Void>
	{
		@Override
		protected Void doInBackground(Void... params)
		{
			// TODO Auto-generated method stub

			// http://www.aaupresensi.tk/report.php
			// http://api.pratamawijaya.com/report.php
			String url = "http://www.aaupresensi.tk/report.php?act=1&id_pelapor=" + siswa.getId()					
					+ "&jenis_apel=" + laporan.getJenis_apel() 
					+ "&tanggal=" + getTanggal()
					+ "&jumlah=" + laporan.getJumlah()
					+ "&kurang=" + laporan.getKurang() + 
					"&hadir=" + laporan.getHadir();

			Utils.TRACE(url);

			// coba upload ke web
			JSONObject jsonObject = json.getJSONFromURL(url);
			resultUpload = json.cekUpload(jsonObject);
			Utils.TRACE("result upload " + resultUpload.getKodeError());
			
			int idReportnya = resultUpload.getIdReport();
			// ambil kode error
			if (resultUpload.getKodeError() == KODE_ERROR)
			{
				// jika tidak error maka upload yang keterangan
				for (int i = 0; i < listKeterangan.size(); i++)
				{
					Utils.TRACE("Upload keterangan :" + (i + 1));
					url = "http://www.aaupresensi.tk/report.php?act=2&id_laporan="
							+ idReportnya							
							+ "&id_siswa=" + listKeterangan.get(i).getId_siswa()
							+ "&jenis_keterangan=" + listKeterangan.get(i).getJenis_keterangan() + "&rumah_sakit="
							+ listKeterangan.get(i).getRumahsakit() + "";
					Utils.TRACE(url);

					Utils.TRACE("" + listKeterangan.get(i).getId_report());
					Utils.TRACE("" + listKeterangan.get(i).getId_siswa());
					Utils.TRACE("" + idSiswa);
					Utils.TRACE("" + listKeterangan.get(i).getJenis_keterangan());
					Utils.TRACE("" + listKeterangan.get(i).getRumahsakit());
					jsonObject = json.getJSONFromURL(url);
					resultUpload = json.cekUpload(jsonObject);

				}

			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			// TODO Auto-generated method stub
			pDialog.dismiss();
			if (resultUpload.getKodeError() == KODE_ERROR)
			{
				Toast.makeText(Halaman3.this, "Data berhasil diupload", Toast.LENGTH_LONG).show();
				Bundle b = new Bundle();
				b.putInt(Halaman1.TAG_ID, siswa.getId());
				b.putString(Halaman1.TAG_NAMA, siswa.getNama());
				b.putString(Halaman1.TAG_KODE, siswa.getKode_aktivasi());
				b.putInt(Halaman1.TAG_SKADRON, siswa.getSkadron());
				b.putInt(Halaman1.TAG_FLIGHT, siswa.getFlight());

				Intent i = new Intent(Halaman3.this, HalamanLaporanActivity.class);
				i.putExtras(b);
				startActivity(i);
				finish();
			} else
			{
				Toast.makeText(Halaman3.this, "Data Gagal diupload :" + resultUpload.getMessageError(),
						Toast.LENGTH_LONG).show();
			}

			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();

			pDialog = new ProgressDialog(Halaman3.this);
			pDialog.setMessage("Loading...");
			pDialog.setCancelable(true);
			pDialog.show();
		}

	}

	private class AsyncTaskEditData extends AsyncTask<Void, Void, Void>
	{
		boolean	flag	= true;

		@Override
		protected Void doInBackground(Void... params)
		{
			// TODO Auto-generated method stub
			// coba delete data
			if (db.deleteKeteranganByReport(id_report))
			{
				Utils.TRACE("Berhasil delete data");
			} else
			{
				flag = false;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			// TODO Auto-generated method stub
			if (flag)
			{

				Bundle bundle = new Bundle();
				bundle.putLong(TAG_ID_REPORT, id_report);
				Intent i = new Intent(Halaman3.this, Halaman2UbahDataActivity.class);
				i.putExtras(bundle);

				startActivity(i);
				finish();
				db.close();

			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute()
		{
			// TODO Auto-generated method stub
			super.onPreExecute();

			pDialog = new ProgressDialog(Halaman3.this);
			pDialog.setMessage("Loading...");
			pDialog.setCancelable(true);
			pDialog.show();
		}
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.hal3BtnLaporkan:

				AlertDialog.Builder alert = new AlertDialog.Builder(Halaman3.this);
				alert.setTitle("Upload Data");
				alert.setMessage("Apakah anda akan upload data ke web ? Data yang sudah diupload tidak dapat dirubah kembali !");
				alert.setPositiveButton("Ya", new DialogInterface.OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						new AsyncTaskHal3UploadKeWeb().execute();

					}
				});
				alert.setNegativeButton("Tidak", new DialogInterface.OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});

				alert.show();
				break;

			case R.id.hal3BtnUbahData:
				new AsyncTaskEditData().execute();
				break;

		}

	}
}
